package com.virjar.hermes.hermesadmin.system;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.google.common.collect.Maps;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;

/**
 * Created by virjar on 2018/7/15.<br>
 * druid数据源
 */
@Configuration
@ConfigurationProperties(prefix = "spring.druid")
@Getter
@Setter
public class DruidDataSourceConfig {
    private String url;

    private String driver_class_name;

    private String username;

    private String password;

    private Integer initialSize;

    private Integer minIdle;

    private Integer maxWait;

    private Integer maxActive;

    private Long minEvictableIdleTimeMillis;

    private String filters;

    @Bean(name = "dataSource")
    @Primary
    public DataSource mysqlDataSource() {

        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(url);
        datasource.setDriverClassName(driver_class_name);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxWait(maxWait);
        datasource.setMaxActive(maxActive);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            throw new IllegalStateException("failed to init druid DataSource", e);
        }
        return datasource;

    }

    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");
        Map<String, String> initParameters = Maps.newHashMap();
        initParameters.put("loginUsername", "druid");// 用户名
        initParameters.put("loginPassword", "druid");// 密码
        initParameters.put("resetEnable", "false");// 禁用HTML页面上的“Reset All”功能
        initParameters.put("allow", "127.0.0.1"); // IP白名单 (没有配置或者为空，则允许所有访问)
        // initParameters.put("deny", "192.168.20.38");// IP黑名单
        // (存在共同时，deny优先于allow)
        servletRegistrationBean.setInitParameters(initParameters);
        return servletRegistrationBean;
    }

}
